package com.kasax.plugin.app.javassist

import com.kasax.plugin.app.LogUtils
import javassist.ClassPool
import javassist.CtClass
import javassist.CtMethod
import org.gradle.api.Project

/**
 * 借助 Javassit 操作 Class 文件
 */
class MyToastInjectByJavassist {
    private static final String TAG = "MyToastInjectByJavassist"

    private static final ClassPool sClsPool = ClassPool.getDefault()
    /**
     * 插入一段toast代码
     * @param path
     * @param project
     */
    static void injectToast(String path, Project project) {
        LogUtils.d("MyToastInjectByJavassist", "injectToast start...")
        // 插入当前路径
        sClsPool.appendClassPath(path)
        // project.android.bootClasspath 加入android.jar，不然找不到android相关的所有类
        sClsPool.appendClassPath(project.android.bootClasspath[0].toString())
        //      // 引入android.os.Bundle包，因为onCreate方法参数有Bundle
        sClsPool.importPackage("android.os.Bundle")
        File dir = new File(path)
        if (dir.isDirectory()) {
            dir.eachFileRecurse { File file ->
                if (file != null && file.exists()) {
                    String filePath = file.absolutePath
                    LogUtils.d("MyToastInjectByJavassist", "file-path: $filePath")
                    if (file.name == "MainActivity.class") {
                        // 获取class
                        // app模块中的MainActivity
                        CtClass ctClass = sClsPool.getCtClass("com.kasax.samv4.MainActivity")
                        LogUtils.d("MyToastInjectByJavassist", "ctClass-path: $ctClass")

                        // 解冻
                        if (ctClass.isFrozen()) {
                            ctClass.defrost()
                        }

                        // 获取method
                        CtMethod ctMethod = ctClass.getDeclaredMethod("onCreate")
                        LogUtils.d("MyToastInjectByJavassist", "ctMethod-path: $ctMethod")

                        String toastStr = "android.widget.Toast.makeText(this, \"插桩toast验证 \", android.widget.Toast.LENGTH_LONG).show();"
                        // 方法尾插入
                        ctMethod.insertAfter(toastStr)
                        // 写入文件
                        ctClass.writeFile(path)
                        // 释放
                        ctClass.detach()
                    }
                }
            }
        }
        LogUtils.d("MyToastInjectByJavassist", "injectToast complete...")
    }
}